package com.yx.frame.log;

import java.text.*;
import java.util.*;

import com.yx.frame.authority.User;

public final class MessageLogClient implements LogWriter {

	private long timeBegin = 0;
	private String logFileName = null;
	private int logLevel = 0;

	public MessageLogClient() {
	}

	public void write(int level, User user, String module, String messageString) {
		if (checkLevel(level)) {
			StringBuffer sb = new StringBuffer();
			String userStr = "系统";
			if (user != null)
				userStr = user.toSimpleString();
			sb.append(dateToString(new Date())).append("  ")
					.append(lOG_MES[level]).append("   [").append(module)
					.append("/").append(userStr).append("] - ")
					.append(messageString).append("\r\n");
			write(sb.toString());
		}
	}

	public void debug(User user, String module, String messageString) {
		write(lOG_DEBUG, user, module, messageString);
	}

	public void info(User user, String module, String messageString) {
		write(lOG_INFO, user, module, messageString);
	}

	public void warn(User user, String module, String messageString) {
		write(lOG_WARN, user, module, messageString);
	}

	public void error(User user, String module, String messageString) {
		write(lOG_ERROR, user, module, messageString);
	}

	public void fatal(User user, String module, String messageString) {
		write(lOG_FATAL, user, module, messageString);
	}

	public void calcTimeBegin() {
		timeBegin = System.currentTimeMillis();
	}

	public long calcTimeEnd() {
		return System.currentTimeMillis() - timeBegin;
	}

	public void setLogFileName(String name) {
		logFileName = name;
	}

	public String getLogFileName() {
		return logFileName;
	}

	public void setLogLevel(int level) {
		logLevel = level;
	}

	public int getLogLevel() {
		return logLevel;
	}

	private void write(String string) {
		MessageLogServer.getInstance().sendMessage(string);
	}

	public static String dateToString(java.util.Date date) {
		SimpleDateFormat formatter = new SimpleDateFormat(
				"yyyy年MM月dd日 HH时mm分ss秒SSS毫秒");

		try {
			return formatter.format(date);
		} catch (Exception e) {
			return date.toString();
		}

	}

	private boolean checkLevel(int level) {
		if (level >= logLevel) {
			return true;
		} else {
			return false;
		}
	}
}
